package com.telnetnz.ticketdesk.service;

import java.util.ArrayList;
import java.util.List;

import net.sf.ehcache.Element;

import org.apache.log4j.Logger;

import com.telnetnz.ticketdesk.bean.Tag;
import com.telnetnz.ticketdesk.common.config.SpringContext;
import com.telnetnz.ticketdesk.dao.entity.TagEntity;
import com.telnetnz.ticketdesk.dao.wrapper.TagWrap;

public class TagService
{
	private static Logger logger = Logger.getLogger(TagService.class);
	private static String CACHE_KEY = "id_";

	/**
	 * Important: This is only for comparison with the updated bean
	 * 
	 * @param uid
	 * @return
	 */
	public static Tag getRawTag(long id)
	{
		TagEntity entity = getWrap().select(id);
		return Tag.adapt(entity);
	}

	/**
	 * Important: This is the only entry to get the ticket bean, including the methods that return instances list
	 * 
	 * @param uid
	 * @return
	 */
	public static Tag getTag(long id)
	{
		Element elm = getWrap().getCache().get(CACHE_KEY + id);
		Tag bean;
		if (elm == null)
		{
			TagEntity entity = getWrap().select(id);
			bean = Tag.adapt(entity);
			if (bean != null)
			{
				getWrap().getCache().put(new Element(CACHE_KEY + id, bean));
			}
		}
		else
		{
			bean = (Tag) elm.getValue();
		}
		return bean;
	}

	public static Tag getTagByName(String name)
	{
		long id = getWrap().selectByName(name);
		return getTag(id);
	}

	public static List<Tag> getAllTags()
	{
		List<Long> ids = getWrap().selectAllTags();
		return adaptIdsList(ids);
	}

	public static void add(Tag tag)
	{
		if (tag == null)
			return;
		getWrap().insert(tag.toEntity());
		getWrap().getCache().remove(CACHE_KEY + tag.getId());
	}

	public static void update(Tag tag)
	{
		if (tag == null)
			return;
		getWrap().update(tag.toEntity());
		getWrap().getCache().remove(CACHE_KEY + tag.getId());
	}

	public static void delete(Tag tag)
	{
		if (tag == null)
			return;
		TicketToTagService.deleteByTagId(tag.getId());
		getWrap().delete(tag.toEntity());
		getWrap().getCache().remove(CACHE_KEY + tag.getId());
	}

	public static List<Tag> adaptIdsList(List<Long> ids)
	{
		List<Tag> tags = new ArrayList<Tag>();
		if (ids != null && ids.size() > 0)
		{
			for (Long id : ids)
			{
				Tag tag = getTag(id);
				if (tag != null)
					tags.add(tag);
			}
		}
		return tags;
	}

	private static TagWrap getWrap()
	{
		return SpringContext.getTagWrap();
	}
}
